import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const user = JSON.parse(localStorage.getItem('user')) || {}

export default new Vuex.Store({
  state: {
    user: {
      account: user.account || '',
      login: user.login || false,
      time: user.time || 0,
    },
    toast: {
      value: false,
      msg: '',
      time: 3000,
    },
  },
  mutations: {
    userLogin(state, account) {
      console.log('account', account);
      if (account !== null) {
        state.user.account = account;
        state.user.login = true;
        state.user.time = +new Date();
      } else {
        state.user.account = '';
        state.user.login = false;
        state.user.time = 0;
      }
      localStorage.setItem('user', JSON.stringify(state.user));
    },
    saveToast(state, data) {
      state.toast = Object.assign(state.toast, data);
    },
  },
  actions: {
    userLogin({ commit }, data) {
      const { account } = data;
      if (account) {
        commit('userLogin', account);
      }
    },
    userLogout({ commit }) {
      commit('userLogin', null);
    },
    checkLogin({ state }) {
      const isLogin = state.user.login && (+new Date() - state.user.time) < (30 * 86400000);
      return isLogin ? Promise.resolve() : Promise.reject();
    },
    toast({ state, commit }, data) {
      commit('saveToast', data);
    },
  },
});
